<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit">编辑</el-button>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="!isEditing"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-input v-model="form.role" disabled />
        </el-form-item>
        
        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useUserStore } from '../store/user';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const formRef = ref(null);
const isEditing = ref(false);

const form = reactive({
  username: '',
  role: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ]
};

onMounted(async () => {
  if (!userStore.userInfo) {
    await userStore.getUserInfoAction();
  }
  form.username = userStore.userInfo?.username || '';
  form.role = userStore.userInfo?.role || '';
});

const handleEdit = () => {
  isEditing.value = true;
};

const handleSave = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    // TODO: 实现保存用户信息的API
    ElMessage.success('保存成功');
    isEditing.value = false;
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

const handleCancel = () => {
  isEditing.value = false;
  form.username = userStore.userInfo?.username || '';
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 